//
//  YQIntegralOrderManageListVC.m
//  MuYing
//
//  Created by tbb on 2020/2/29.
//  Copyright © 2020 TBB. All rights reserved.
//

#import "YQIntegralOrderManageListVC.h"
#import "YQPIntegerPayView.h"
#import "YQIntegralOrderDetailsVC.h"

#import "YQOrderLogisticsWriteVC.h"
@interface YQIntegralOrderManageListVC ()<YQOrderManageBtnActionCellDelegate>
@property (strong, nonatomic) NSMutableArray *orderArray;

@property (strong, nonatomic) YQPOrderModel *orderModel;

@property (assign, nonatomic) NSInteger orderType;

@property (strong, nonatomic) YQPIntegerPayView *integeView;

@end

@implementation YQIntegralOrderManageListVC

- (void)viewDidLoad {
    [super viewDidLoad];
    if (self.type == 0) {
        self.orderType = 5;
    } else {
        self.orderType = self.type - 1;
    }

    self.orderArray = NSMutableArray.new;
    [self setupRefresh];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setupRefresh];

}

- (YQPIntegerPayView *)integeView
{
    if (!_integeView) {
        _integeView = [YQPIntegerPayView new];
    }
    return _integeView;
}

- (void)setupRefresh
{
    self.listTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self getUserOrdersApi:YES];
    }];

    self.listTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        if (self.orderArray.count < 10) {
            [self.listTableView.mj_footer endRefreshingWithNoMoreData];
            return ;
        }
        self.page ++;

        [self getUserOrdersApi:NO];
    }];
    // 自动改变透明度
    self.listTableView.mj_header.automaticallyChangeAlpha = YES;
    [self.listTableView.mj_header beginRefreshing];
}
#pragma amrk - POST 查询我的订单列表
- (void)getUserOrdersApi:(BOOL)isReload
{
    if (isReload) {
        self.page = 1;
    }
    
    NSMutableDictionary *dic = NSMutableDictionary.new;
    dic[@"page"] = @(self.page);
    dic[@"limit"] = @(10);
    dic[@"type"] = @(self.orderType);

    

    [YQPNetWorkingManager sendPostRequest:kPOST_ORDER_LIST_URL parameters:dic success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        if (responseObject.code == 0) {
            if (self.page == 1) {
                [self.orderArray removeAllObjects];
            }
            self.orderModel = [YQPOrderModel mj_objectWithKeyValues:responseObject.data];
            [self.orderArray addObjectsFromArray:self.orderModel.list];
            if (self.orderArray.count == 0) {
                [MBProgressHUD showMessage:kYQLS(@"暂无订单")];
            } else {
                
            }
            [self.listTableView reloadData];
        }else{
            YQUITIPSERROR(responseObject.msg)
        }

        [self.listTableView.mj_header endRefreshing];
        [self.listTableView.mj_footer endRefreshing];

    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        YQUITIPSERROR(error)
        [self.listTableView.mj_header endRefreshing];
        [self.listTableView.mj_footer endRefreshing];
    }];
}
-(void)setupView {
    [super setupView];
    self.listTableView.backgroundColor = kAPPTABLEVIEW_BG_COLOR;
    self.listTableView.frame = CGRectMake(0, 0, kYQPScreenWidth, kYQPScreenHeight-Height_NavBar-kHeight_Botton_SafeArea-44);
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManageStateCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManageGoodsCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManagePriceCell")
    kYQREGISTERTABLEVIEWNIBCELL(@"YQOrderManageBtnActionCell")
    
}

#pragma mark - JXCategoryListContentViewDelegate

- (UIView *)listView {
    return self.view;
}

- (UIScrollView *)listScrollView {
    return self.listTableView;
}
#pragma mark - JXCategoryListContentViewDelegate end

#pragma mark - UITableViewDelegate, UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.orderArray.count;
}

- (NSInteger)tableView:(nonnull UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    YQPOrderEntityModel *model = self.orderArray[section];
    if ([model.orderStatus isEqualToString:@"4"] || [model.orderStatus isEqualToString:@"1"]) {
        return 3;

    }
    return 4;
}

- (nonnull UITableViewCell *)tableView:(nonnull UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    YQPOrderEntityModel *model = nil;
    if (indexPath.row < self.orderArray.count) {
        model = self.orderArray[indexPath.section];
    }
    if (indexPath.row == 0) {
        YQOrderManageStateCell *stateCell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManageStateCell"];
        [stateCell setModel:model];

        return stateCell;
    }
    else if (indexPath.row == 1) {
        YQOrderManageGoodsCell *goodsCell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManageGoodsCell"];

        [goodsCell setModel:model];

        return goodsCell;
    }else if (indexPath.row == 2){
        YQOrderManagePriceCell *priceCell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManagePriceCell"];
        [priceCell setModel:model];

        return priceCell;
    }else{
        YQOrderManageBtnActionCell *cell = [tableView dequeueReusableCellWithIdentifier:@"YQOrderManageBtnActionCell"];
        cell.indexPath = indexPath;

        cell.delegate = self;
        if ([model.orderStatus isEqualToString:@"0"]) {
            [cell.rightBtn setTitle:kYQLS(@"立即支付") forState:(UIControlStateNormal)];
            [cell.leftBtn setTitle:kYQLS(@"取消订单") forState:(UIControlStateNormal)];
            cell.leftBtn.hidden = NO;
        }else if ([model.orderStatus isEqualToString:@"2"]) {
            [cell.rightBtn setTitle:kYQLS(@"确认收货") forState:(UIControlStateNormal)];
            cell.leftBtn.hidden = YES;

        }else if ([model.orderStatus isEqualToString:@"3"]) {
            [cell.rightBtn setTitle:kYQLS(@"删除订单") forState:(UIControlStateNormal)];
            cell.leftBtn.hidden = YES;

        }
        return cell;
    }
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    YQPOrderEntityModel *model = self.orderArray[indexPath.section];

    if (indexPath.row == 0) {
        return 47;
    }else if (indexPath.row == 1) {
        return 104;
    }else if(indexPath.row == 2) {
        return 32;
    }else if (indexPath.row == 3){
        if ([model.orderStatus isEqualToString:@"4"] || [model.orderStatus isEqualToString:@"1"]) {
            return 0.01;

        }
    }
    return 52;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YQPOrderEntityModel *model = self.orderArray[indexPath.section];
    YQIntegralOrderDetailsVC *vc = [[YQIntegralOrderDetailsVC alloc] init];
    vc.model = model;
    kYQPUSH(vc);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}
#pragma mark - UITableViewDelegate, UITableViewDataSource end

#pragma makr -- YQOrderManageBtnActionCellDelegate---列表按钮点击代理事件
-(void)orderSateBtnActionDidSelect:(NSIndexPath *)indexPath :(NSString *)currentTitle {
    YQPOrderEntityModel *model = self.orderArray[indexPath.section];
    if ([currentTitle isEqualToString:kYQLS(@"取消订单")]) {
        [self cancelOrder:model];
    }else if ([currentTitle isEqualToString:kYQLS(@"立即支付")]){
        self.integeView.labSubTitle.text = [NSString stringWithFormat:@"%@ %@",model.totalIntegralAmount,kYQLS(@"积分")];;
        
        [self.integeView show];
        MJWeakSelf
        [self.integeView setSureBlock:^{
            [weakSelf.integeView dismissView];
            [weakSelf payOrderByIntegerApi:model.integralOrderId];

        }];
    }else if ([currentTitle isEqualToString:kYQLS(@"查看物流")]){
        YQOrderLogisticsWriteVC *writeVC = [[YQOrderLogisticsWriteVC alloc] init];
        [self.navigationController pushViewController:writeVC animated:true];
    }else if ([currentTitle isEqualToString:kYQLS(@"确认收货")]){
        NSString *url = [NSString stringWithFormat:@"%@%@",kPOST_INTEGER_RECEIVE_URL,model.integralOrderId];
        [YQPNetWorkingManager sendPostRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
            if (responseObject.code == 0) {
                [MBProgressHUD showMessage:kYQLS(@"收货成功")];
                [self setupRefresh];
            }else{
                YQUITIPSERROR(responseObject.msg)
            }
        } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
            YQUITIPSERROR(error)
        }];
    }else if ([currentTitle isEqualToString:kYQLS(@"删除订单")]){
        NSString *url = [NSString stringWithFormat:@"%@%@",kPOST_DELETE_ORDER_URL,model.integralOrderId];
        [YQPNetWorkingManager sendPostRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
            [MBProgressHUD showMessage:kYQLS(@"删除成功")];
            [self setupRefresh];
        } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
            
        }];
    }
}

- (void)cancelOrder:(YQPOrderEntityModel *)model
{
    QMUIAlertController *alert = [[QMUIAlertController alloc] initWithTitle:kYQLS(@"确定取消该订单?") message:@"" preferredStyle:(QMUIAlertControllerStyleAlert)];
    
    [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"我再想一想") style:(QMUIAlertActionStyleCancel) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        
    }]];
    alert.alertCancelButtonAttributes = @{NSForegroundColorAttributeName:kAPPThemeColor,NSFontAttributeName:UIFontBoldMake(17),NSKernAttributeName:@(0)};
    MJWeakSelf
    [alert addAction:[QMUIAlertAction actionWithTitle:kYQLS(@"确定") style:(QMUIAlertActionStyleDefault) handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        [weakSelf cancelOrderApi:model];

        
    }]];
    alert.alertButtonAttributes = @{NSForegroundColorAttributeName:HexColor(0xB7B7B7),NSFontAttributeName:kSystemMedium(17),NSKernAttributeName:@(0)};
    
    [alert showWithAnimated:YES];
}

#pragma mark - 积分支付
- (void)payOrderByIntegerApi:(NSString *)integralOrderId
{
    NSString *url = [NSString stringWithFormat:@"%@%@",kPOST_INTEGER_PAY_URL,integralOrderId];
    [YQPNetWorkingManager sendPostRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        
        [MBProgressHUD showMessage:kYQLS(@"支付成功")];
        
        [self setupRefresh];
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}
#pragma makr - 取消订单 http://192.168.3.101:6061/yiqi-api/api/integral/cancel/order/29
- (void)cancelOrderApi:(YQPOrderEntityModel *)model
{
    NSString *url = [NSString stringWithFormat:@"%@%@",kPOST_CANCEL_ORDER_URL,model.integralOrderId];
    [YQPNetWorkingManager sendPostRequest:url parameters:@{} success:^(YQPNetWorkingBaseModel * _Nonnull responseObject) {
        [MBProgressHUD showMessage:kYQLS(@"订单已取消")];
        MYShopSalesOrderSucceedVC *succeedVC = [[MYShopSalesOrderSucceedVC alloc]initWithNibName:@"MYShopSalesOrderSucceedVC" bundle:nil];
        succeedVC.isIntegral = YES;
        succeedVC.paySuceedLbText = kYQLS(@"订单已取消");
        succeedVC.paySuceedBtnText = kYQLS(@"前往商城");
        
        succeedVC.navigationItem.title = kYQLS(@"前往积分商城");
        succeedVC.goBarkToVC = @"MYCreditsMallVC";
        [self.navigationController pushViewController:succeedVC animated:true];
    } failure:^(NSUInteger statusCode, NSString * _Nonnull error) {
        
    }];
}
#pragma makr -- YQOrderManageBtnActionCellDelegate end

@end
